/**
 * 内容小标题
 */
Vue.component("content-title", {
    props: {
        // 内容标题
        title: {
            type: "string",
            default: ""
        }
    },
    template: `
        <div class="content-container">
            <div class="content-title-box">
                <div class="title-icon"></div>
                <span>{{title}}</span>
            </div>
            <div class="content-bottom-box">
                <slot></slot>
            </div>
        </div>
    `,
    data() {
        return {

        }
    },
    methods: {

    },
    mounted() {

    },
});

/**
 * 暂无数据
 */
Vue.component("no-data-t", {
    props: {
        // 暂无数据提示
        text: {
            type: "string",
            default: "暂无数据"
        },
        loading: {
            type: Boolean,
            default: false
        },
        loadingText: {
            type: "string",
            default: "加载中···"
        }
    },
    template: `
        <div class="no-data-t">
            <slot name="top"></slot>
            <p>{{loading ? loadingText : text}}</p>
            <slot name="bottom"></slot>
        </div>
    `,
});

/**
 * 头部组件
 */
Vue.component("head-component", {
    props: {
        title: {
            type: String,
            default: "高标准农田数字化管理"
        },
        name: {
            type: String,
            default: "运行监测"
        }
    },
    template: `
        <div class="page-header">
            <div class="page-header-left">
                <div>
                    <img src="../../resources/img/dp-layout/ldt.png" alt="">
                    <span>{{headDate[0]}} {{headDate[2]}}</span>
                </div>
            </div>
            <div class="page-header-center">
                <span>{{title}}</span>
                <el-dropdown trigger="click" @command="handleCommand">
                    <div class="little-title">
                        <span>——{{name}}</span>
                        <img src="./img/xl.png" alt="">
                    </div>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="(item,index) in dropdownList" :key="index + 'drop'" :command="item.url">{{item.name}}</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <div class="page-header-right" @click="pageBack">
                <img src="./img/fh.png" alt="">
            </div>
        </div>
    `,
    data() {
        return {
            // 头部日期索引
            weekData: ["日", "一", "二", "三", "四", "五", "六"],
            // 头部时间
            date: new Date(),
            // 头部时间循环实例
            setIntervalExample: null,
            // 下拉菜单
            dropdownList: [
                { name: "运行监测", url: "../operation-monitoring-dp/index.html" },
                { name: "巡查管护", url: "../dp-patrol-guard/index.html" },
            ]
        }
    },
    computed: {
        // 头部日期
        headDate() {
            let arr = [];
            arr[0] = tpUtils.parseTime(this.date, "{y}-{m}-{d}");
            arr[1] = this.weekData[this.date.getDay()];
            arr[2] = tpUtils.parseTime(this.date, "{h}:{i}:{s}");
            return arr;
        },
    },
    methods: {
        // 返回上一页
        pageBack() {
            window.location.href = "../dp-index/index.html?pageCode=index";
        },
        /**
         * 头部下拉点击
         */
        handleCommand(url) {
            window.location.href = url;
        }
    },
    mounted() {
        // 动态更新  data  中的 时间  以此来更新 计算属性的时间
        this.setIntervalExample = setInterval(() => {
            this.date = new Date();
        }, 1000);
    },
    beforeDestroy() {
        clearInterval(this.setIntervalExample);
    },
})

/**
 * 监测站点类型分布
 */
Vue.component("monitoring-site-distribution", {
    props: {
        // 项目下终端列表
        projectTerminalList: {
            type: String,
            default: ""
        },
        // 加载动画
        loading: {
            type: Boolean,
            default: false
        }
    },
    template: `
        <content-title title="监测站点类型分布">
            <div class="monitoring-box" v-show="monitorTypeList.length" v-loading="loading">
                <div class="monitoring-type" v-for="(item,index) in monitorTypeList" :key="index + 'monitor'">
                    <img :src="item.icon" alt="">
                    <p>
                        <span>{{item.value}}</span>
                        <span>{{item.name}}</span>
                    </p>
                </div>
            </div>
        </content-title>
    `,
    data() {
        return {
            // 监测站点列表
            monitorTypeList: [
                { name: '气象', value: '0', icon: "./img/qix.png" },
                { name: '水', value: '0', icon: "./img/shui.png" },
                { name: '土壤', value: '0', icon: "./img/tr.png" },
                { name: '病害', value: '0', icon: "./img/bh.png" },
                { name: '虫害', value: '0', icon: "./img/ch.png" },
                { name: '其他', value: '0', icon: "./img/qt.png" },
            ],
        }
    },
    watch: {
        projectTerminalList(val) {
            let qxNum = 0, swNum = 0, trNum = 0, bhNum = 0, chNum = 0, qtNum = 0;
            val.forEach(item => {
                switch (item.terminalTypeName) {
                    case "气象":
                        qxNum++;
                        break;
                    case "水质":
                        swNum++;
                        break;
                    case "土壤":
                        trNum++;
                        break;
                    case "病害":
                        bhNum++;
                        break;
                    case "虫害":
                        chNum++;
                        break;
                    default:
                        qtNum++;
                        break;
                }
            });
            this.monitorTypeList = [
                { name: '气象', value: qxNum || '0', icon: "./img/qix.png" },
                { name: '水', value: swNum || '0', icon: "./img/shui.png" },
                { name: '土壤', value: trNum || '0', icon: "./img/tr.png" },
                { name: '病害', value: bhNum || '0', icon: "./img/bh.png" },
                { name: '虫害', value: chNum || '0', icon: "./img/ch.png" },
                { name: '其他', value: qtNum || '0', icon: "./img/qt.png" },
            ]
        }
    },
});

/**
 * 设备信息
 */
Vue.component("device-info", {
    props: {
        // 项目Id
        projectId: {
            type: [Number, String],
            default: ""
        },
        // 项目下终端列表
        projectTerminalList: {
            type: String,
            default: ""
        },
        // 加载动画
        loading: {
            type: Boolean,
            default: false
        }
    },
    template: `
        <content-title title="设备信息">
            <div class="device-info">
                <div class="device-info-table" v-show="projectId !== ''" v-loading="loading">
                    <div class="device-info-table-header">
                        <p>设备类型</p>
                        <p>设备编号</p>
                        <p>设备预警次数</p>
                    </div>
                    
                    <div class="device-info-table-content" v-show="deviceInfoList.length">
                        <div class="device-info-table-content-item" v-for="(item,index) in deviceInfoList" :key="index + 'device'">
                            <p>{{item.name}}</p>
                            <p>{{item.serialNum}}</p>
                            <p>{{item.num}}</p>
                        </div>
                    </div>
                    <div class="device-info-table-content" v-show="!deviceInfoList.length">
                        <no-data-t></no-data-t>
                    </div>
                </div>
                <div class="device-info-chart" v-loading="areaLoading" v-show="projectId==='' && deviceInfoChartsList.length">
                    <div class="device-info-chart-item" v-for="(item,index) in deviceInfoChartsList" :key="index + 'Charts'">
                        <span>{{item.name}}</span>
                        <div class="device-info-progress-bac">
                            <div class="device-info-progress" :style="{width: item.pre + '%'}"></div>
                        </div>
                        <p>{{item.num}}</p>
                    </div>
                </div>
                <no-data-t v-show="!projectId && !deviceInfoChartsList.length"></no-data-t>
            </div>
        </content-title>
    `,
    data() {
        return {
            // 设备信息展示类型 1 表格  2  柱状
            deviceInfoType: 1,
            // 设备信息列表
            deviceInfoList: [],
            // 设备信息图表列表
            deviceInfoChartsList: [],
            // 各区域加载动画
            areaLoading: false,
        }
    },
    watch: {
        // 项目ID 改变
        projectTerminalList(val) {
            this.deviceInfoList = val.map(item => {
                return {
                    name: item.terminalTypeName || "其他",
                    serialNum: item.terminal_serial,
                    num: item.alarm_count || 0
                }
            });
        }
    },
    methods: {
        /**
         * 获取个各区域项目终端数量
         */
        getProjectDeviceInfo() {
            this.areaLoading = true;
            let params = {};
            tpHttp.post(this, "action=com.top.local.hsfpl.operationMonitorScreen.loadTermAreaDistributionData", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && data.length) {
                    let allNum = data.reduce((pre, next) => {
                        return pre + next.term_count
                    }, 0);
                    this.deviceInfoChartsList = data.map(item => {
                        return {
                            name: item.area_name,
                            pre: (item.term_count / allNum * 100).toFixed(2),
                            num: item.term_count
                        }
                    });
                    this.deviceInfoChartsList.sort((a, b) => {
                        return b.num - a.num
                    })
                } else {
                    this.deviceInfoChartsList = [];
                }
                this.areaLoading = false;
            })
        },
    },
    mounted() {
        this.getProjectDeviceInfo();
    }
});


/**
 * 最新预警
 */
Vue.component("new-warning", {
    props: {
        // 项目Id
        projectIds: {
            type: [Number, String],
            default: ""
        },
    },
    template: `
        <content-title title="最新预警">
            <div class="new-warning">
                <div class="device-info-table">
                    <div class="device-info-table-header">
                        <p>预警时间</p>
                        <p>预警设备</p>
                        <p>预警内容</p>
                    </div>
                    
                    <div class="device-info-table-content" v-show="warningList.length" v-loading="warnLoading">
                        <div class="device-info-table-content-item" v-for="(item,index) in warningList" :key="index + 'warn'">
                            <p>{{item.alarm_time}}</p>
                            <p>{{item.device_name}}</p>
                            <p><span>{{item.suggest}}</span></p>
                        </div>
                    </div>
                    <div class="device-info-table-content" v-show="!warningList.length" v-loading="warnLoading">
                        <no-data-t></no-data-t>
                    </div>
                </div>
            </div>
        </content-title>
    `,
    data() {
        return {
            // 预警列表
            warningList: [],
            // 加载
            warnLoading: false
        }
    },
    watch: {
        projectIds(val) {
            this.getWarningList();
        }
    },
    methods: {
        /**
         * 获取预警列表
         */
        getWarningList() {
            this.warnLoading = true;
            let params = { "projectIds": this.projectIds, "page": 1, "size": 10 };
            tpHttp.post(this, "action=com.top.local.hsfpl.operationMonitorScreen.findRealTimeAlarmPageListBy", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && data.list && data.list.length) {
                    this.warningList = data.list;
                } else {
                    this.warningList = [];
                }
                this.warnLoading = false;
            })
        }
    },
});

/**
 * 设备报警类型趋势
 */
Vue.component("device-alarm-trend", {
    props: {
        projectIds: {
            type: Array,
            default: []
        }
    },
    template: `
        <content-title title="设备报警类型趋势">
            <div class="device-alarm-type-trend">
                <div class="top-search-type">
                    <span :class="warnDateTypeActive == item.value?'warn-btn-active':''" v-for="(item,index) in warnDateType" :key="index + 'date'" @click="warnTypeClick(item.value)">{{item.name}}</span>
                </div>
                <div v-loading="loading" id="device-alarm-chart" v-if="deviceAlarmTypeData.length"></div>
                <no-data-t v-loading="loading" v-show="!deviceAlarmTypeData.length"></no-data-t>
            </div>
        </content-title>
    `,
    data() {
        return {
            // 设备报警类型趋势头部时间类型
            warnDateType: [
                { name: "近7日", value: 1 },
                { name: "本月", value: 2 },
            ],
            // 时间类型选中
            warnDateTypeActive: 1,
            // 图表数据
            deviceAlarmTypeData: [],

            // 数据加载动画
            loading: false
        }
    },
    watch: {
        // 项目ID传入
        projectIds() {
            this.getDeviceAlarmTypeData();
        }
    },
    methods: {
        /**
         * 时间类型点击
         * @param {*} val 
         */
        warnTypeClick(val) {
            this.warnDateTypeActive = val;
            this.getDeviceAlarmTypeData();
        },
        /**
         * 获取告警曲线数据
         */
        getDeviceAlarmTypeData() {
            this.loading = true;
            let startDate = "", endDate = "";
            switch (this.warnDateTypeActive) {
                case 1:
                    startDate = tpUtils.parseTime(new Date().getTime() - 6 * 24 * 60 * 60 * 1000, "{y}-{m}-{d}");
                    endDate = tpUtils.parseTime(new Date().getTime(), "{y}-{m}-{d}");
                    break;
                case 2:
                    startDate = tpUtils.parseTime(new Date().getTime(), "{y}-{m}") + "-01";
                    endDate = tpUtils.parseTime(new Date().getTime(), "{y}-{m}-{d}");
                    break;
            }
            let params = { "projectIds": this.projectIds, "startDate": startDate, "endDate": endDate };
            tpHttp.post(this, "action=com.top.local.hsfpl.operationMonitorScreen.mainTypeAlarmCountByProjectIds", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && JSON.stringify(data) != "{}") {
                    let xAxisData = [], deviceAlarmTypeData = [];
                    if (data.sensor && data.sensor.length) {
                        xAxisData = data.sensor.map(item => item.stat_date);
                        deviceAlarmTypeData.push({
                            name: "传感器",
                            value: data.sensor.map(item => item.alarm_count)
                        });
                    }
                    if (data.fault && data.fault.length) {
                        deviceAlarmTypeData.push({
                            name: "故障",
                            value: data.fault.map(item => item.alarm_count)
                        })
                    }
                    if (data.status && data.status.length) {
                        deviceAlarmTypeData.push({
                            name: "离线",
                            value: data.status.map(item => item.alarm_count)
                        })
                    }
                    this.deviceAlarmTypeData = deviceAlarmTypeData;
                    this.initChart(xAxisData);
                } else {
                    this.deviceAlarmTypeData = [];
                }
                this.loading = false;
            })
        },
        /**
         * 初始化图表
         */
        initChart(xAxisData) {
            let seriesData = [];
            seriesData = this.deviceAlarmTypeData.map(item => {
                return {
                    name: item.name,
                    data: item.value,
                    type: 'line',
                    showSymbol: false,
                }
            })
            this.$nextTick(() => {
                initDeviceAlarmTypeLineChart(xAxisData, seriesData);
            });
        }
    },
    mounted() {
    },
});

/**
 * 问题处理情况
 */
Vue.component("problem-handle", {
    props: {
        projectIds: {
            type: Array,
            default: []
        }
    },
    template: `
        <content-title title="问题处理情况">
            <div class="problem-box">
                <div class="problem-box-left">
                    <div id="problem-chart-box"></div>
                </div>
                <div class="problem-box-right">
                    <div class="problem-table-header">
                        <p>分类</p>
                        <p>数量（条）</p>
                        <p>占比</p>
                    </div>
                    <div class="problem-table-item" v-for="(item,index) in problemHandleTable" :key="index + 'problem'">
                        <p>
                            <span :style="{background: item.color}" class="dot"></span>
                            <span>{{item.name}}</span>
                        </p>
                        <p :style="{color: item.color}">{{item.num}}</p>
                        <p :style="{color: item.color}">{{item.percent}}</p>
                    </div>
                </div>
            </div>
        </content-title>
    `,
    data() {
        return {
            // 问题处理情况表格数据
            problemHandleTable: [
                { name: '未处理', num: 0, percent: '0%', color: '#FFA800' },
                { name: '已处理', num: 0, percent: '0%', color: '#00B8FF' },
                { name: '误报', num: 0, percent: '0%', color: '#00FFA8' },
            ]
        }
    },
    watch: {
        // 项目ID传入
        projectIds() {
            this.getProblemHandleData();
        }
    },
    methods: {
        /**
         * 获取各状态下的告警数量
         */
        getProblemHandleData() {
            let params = { "projectIds": this.projectIds };
            tpHttp.post(this, "action=com.top.local.hsfpl.operationMonitorScreen.alarmStatusCountByProjectIds", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && JSON.stringify(data) != "{}") {
                    let total = data.unprocessed_count + data.processed_count + data.false_alarm_count;
                    this.problemHandleTable = [
                        { name: '未处理', num: data.unprocessed_count, percent: (data.unprocessed_count / total * 100).toFixed(2) + '%', color: '#FFA800' },
                        { name: '已处理', num: data.processed_count, percent: (data.processed_count / total * 100).toFixed(2) + '%', color: '#00B8FF' },
                        { name: '误报', num: data.false_alarm_count, percent: (data.false_alarm_count / total * 100).toFixed(2) + '%', color: '#00FFA8' },
                    ];
                    bus.$emit("problemHandleTotal", total);
                } else {
                    this.problemHandleTable = [
                        { name: '未处理', num: 0, percent: '0%', color: '#FFA800' },
                        { name: '已处理', num: 0, percent: '0%', color: '#00B8FF' },
                        { name: '误报', num: 0, percent: '0%', color: '#00FFA8' },
                    ];
                }
                this.initChart();
            })
        },
        /**
         * 初始化图表
         */
        initChart() {
            let seriesData = this.problemHandleTable.map(item => {
                return {
                    name: item.name,
                    value: item.num
                }
            })
            this.$nextTick(() => {
                initProblemHandlePieChart(seriesData);
            });
        }
    },
    mounted() {
        this.initChart();
    },
});

/**
 * 站点实时监测数据
 */
Vue.component("site-monitoring", {
    props: {
        // 页面选中项目
        projectId: {
            type: [Number, String],
            default: ""
        },
        // 站点检测项目下拉列表
        projectList: {
            type: [Array],
            default: []
        },
        // 项目下终端列表
        projectTerminalList: {
            type: String,
            default: ""
        },
    },
    template: `
        <content-title title="站点实时监测数据">
            <div class="site-real-monitor-data">
                <div class="site-real-monitor-data-top">
                    <!--<el-select clearable filterable v-model="siteMonitorProject" placeholder="请选择">
                        <el-option v-for="item in siteMonitorProjectList" :key="item.projectId" :label="item.name" :value="item.projectId">
                        </el-option>
                    </el-select>-->
                    <div class="site-real-monitor-type">
                        <span :class="siteMonitorType == item.value ? 'active':''" v-for="(item,index) in siteMonitorTypeList" :key="index + 'mon'" @click="siteMonitorTypeClick(item)">{{item.label}}</span>
                    </div>
                </div>
                <div class="site-real-monitor-data-content" v-show="siteMonitorType != 3">
                    <div class="site-real-monitor-table-head">
                        <p :style="{width: item.width || 'calc(100% / '+ tableHeader.length +')', color: item.color}" v-for="(item,index) in tableHeader" :key="index + 'weather'">{{item.label}}</p>
                    </div>
                    <div class="site-real-monitor-table-content" v-loading="tableLoading" v-show="tableData.length">
                        <div class="site-real-monitor-table-item" v-for="(item,index) in tableData" :key="index + 'wtab'">
                            <p :style="{width: el.width || 'calc(100% / '+ tableHeader.length +')', color: el.color}" v-for="(el,v) in tableHeader" :key="v + 'wpro'">{{item[el.props]}}</p>
                        </div>
                    </div>
                    <div class="site-real-monitor-table-content" v-loading="tableLoading" v-show="!tableData.length">
                        <no-data-t></no-data-t>
                    </div>
                </div>
                <div class="site-real-monitor-data-content" v-loading="tableLoading" v-show="siteMonitorType == 3">
                    <div class="site-real-monitor-insect" v-show="insectList.length">
                        <!-- Swiper -->
                        <div class="swiper myInsectSwiper">
                            <div class="swiper-wrapper">
                                <div class="swiper-slide" v-for="(item,index) in insectList" :key="index + 'insect'">
                                    <div class="site-real-monitor-insect-box">
                                        <div class="site-real-monitor-insect-top">
                                            <img :src="item.img_url" alt="">
                                            <p>{{item.create_time}}</p>
                                        </div>
                                        <div class="site-real-monitor-insect-bottom">
                                            <span>虫子{{item.allNum}}头</span>
                                            <!--<el-popover placement="top" width="230" trigger="click">
                                                <div class="insect-detail-box">
                                                    <div class="insect-detail-table" v-show="item.insectInfo.length">
                                                        <p v-for="(el,i) in item.insectInfo" :key="i + 'insdetail'">
                                                            <span>{{el.insectTypeName}}</span>
                                                            <span>{{el.number}}只</span>
                                                        </p>
                                                    </div>
                                                    <span v-show="!item.insectInfo.length">暂无虫子数据</span>
                                                </div>
                                                <p slot="reference">详情<i class="el-icon-d-arrow-right"></i></p>
                                            </el-popover>-->
                                            <p @click="indectDetailClick(item)">详情<i class="el-icon-d-arrow-right"></i></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="insect-swiper-next"><i class="el-icon-arrow-right"></i></div>
                        <div class="insect-swiper-prev"><i class="el-icon-arrow-left"></i></div>
                    </div>
                    <no-data-t v-show="!insectList.length"></no-data-t>
                </div>
                <el-dialog title="详情" class="dp-mark-dialog__wrapper" custom-class="dp-mark-dialog"  :visible.sync="detailsData.visible" width="60%" append-to-body>
                    <div class="insect-dialog-detail-box">
                        <div class="konva-container" style="height:500px;" v-loading="detailsData.loading"></div>
                        <div class="legend-list-konvas">
                            <div class="li-item-header">
                                <span>标记色</span>
                                <span>虫子名称</span>
                                <span>虫子数量</span>
                            </div>
                            <div class="li-item-box" v-show="detailsData.legendList.length">
                                <div class="li-item" v-for="item of detailsData.legendList">
                                    <span>
                                        <span class="dot" :style="{background:item.bgColor}"></span>
                                    </span>
                                    <span>{{item.insect_name}}</span>
                                    <span>{{item.number}}头</span>
                                </div>
                            </div>
                            <div class="li-item-box" v-show="!detailsData.legendList.length">
                                <no-data-t></no-data-t>
                            </div>
                        </div>
                    </div>
                </el-dialog>
            </div>
        </content-title>
    `,
    data() {
        return {
            // 站点检测项目下拉列表
            siteMonitorProjectList: [],
            // 站点检测项目选中
            siteMonitorProject: "",
            // 传感器数据
            sensorList: [],
            // 站点检测展示类型列表
            siteMonitorTypeList: [
                { label: "气象", value: 1 },
                { label: "土壤", value: 2 },
                { label: "虫情", value: 3 },
                { label: "水质", value: 4 },
            ],
            // 站点检测展示类型选中
            siteMonitorType: 1,
            // 展示表格头部
            tableHeader: [],
            // 展示表格数据
            tableData: [],
            // 气象表格头部
            weatherTableHeader: [
                { label: "设备名称", width: "20%", props: "serial_num" },
                { label: "上报时间", width: "15%", props: "collect_time" },
                { label: "温度(℃)", width: "", props: "temperature", color: "#69fff6", sensor_type_id: 177 },
                { label: "湿度(%RH)", width: "", props: "humidity", color: "#19e880", sensor_type_id: 178 },
                { label: "风速(m/s)", width: "", props: "windSpeed", color: "#45e819", sensor_type_id: 181 },
                { label: "风向", width: "", props: "windDirection", color: "#e1e819", sensor_type_id: 180 },
                { label: "雨量(mm)", width: "", props: "rainfall", color: "#e8bf19", sensor_type_id: 176 },
                { label: "光照(Lux)", width: "", props: "illumination", color: "#ff860f", sensor_type_id: 186 },
            ],
            // 土壤表格头部
            soilTableHeader: [
                { label: "设备名称", width: "20%", props: "serial_num" },
                { label: "上报时间", width: "15%", props: "collect_time" },
                { label: "温度(℃)", width: "", props: "temp", sensor_type_id: 161 },
                { label: "湿度(%RH)", width: "", props: "humidity", sensor_type_id: 162 }
            ],
            // 水质表格头部
            waterTableHeader: [
                { label: "设备名称", width: "20%", props: "serial_num" },
                { label: "上报时间", width: "15%", props: "collect_time" },
                { label: "氨氮(mg/L)", width: "", props: "adn", sensor_type_id: 214 },
                { label: "溶解氧(mg/L)", width: "", props: "rjy", sensor_type_id: 213 },
                { label: "水位(mm)", width: "", props: "swei", sensor_type_id: 217 },
                { label: "水温(℃)", width: "", props: "sw", sensor_type_id: 212 },
                { label: "电导(uS/cm)", width: "", props: "ddl", sensor_type_id: 216 },
                { label: "pH值", width: "", props: "ph", sensor_type_id: 211 },
                { label: "浊度(NTU)", width: "", props: "zd", sensor_type_id: 210 },
                { label: "总磷(mg/Kg)", width: "", props: "zl", sensor_type_id: 242 },
            ],
            // 虫情列表
            insectList: [],
            // 获取虫情数据的页数 和  条数
            insectPagaination: {
                page: 1,
                size: 20,
                total: 0
            },
            // 虫情轮播实例
            insectSwiper: null,
            // 虫情详情弹框
            detailsData: {
                stage: null,
                layer: null,
                group: null,
                scale: 1,
                visible: false,
                legendList: [],
                loading: false
            },

            // 当前设备序列号们
            curSerialNums: "",

            // 加载动画
            tableLoading: false,
        }
    },
    watch: {
        // 页面选中项目
        projectId(val) {
            this.siteMonitorProject = val;
        },
        siteMonitorProject(value) {
            // this.getSensorRealData();
        },
        projectList(value) {
            this.siteMonitorProjectList = value;
            // this.getSensorRealData();
        },
        projectTerminalList() {
            this.getSensorRealData();
        }
    },
    methods: {
        /**
         * 获取传感器实时数据
         */
        getSensorRealData() {
            this.tableLoading = true;
            let startDate = tpUtils.parseTime(new Date().getTime() - 6 * 24 * 60 * 60 * 1000, "{y}-{m}-{d}");
            endDate = tpUtils.parseTime(new Date().getTime(), "{y}-{m}-{d}");
            let serialNumArr = [], serialNumList = [], serialNums = "";
            if (this.siteMonitorProject == "") {
                let arr = []
                this.siteMonitorProjectList.forEach(item => {
                    arr = arr.concat(item.term_list || []);
                });
                serialNumArr = arr;
            } else {
                let obj = this.siteMonitorProjectList.find(item => item.projectId == this.siteMonitorProject);
                serialNumArr = obj && obj.term_list || [];
            }
            switch (this.siteMonitorType) {
                case 1:
                    serialNumList = serialNumArr.filter(item => [3, 20, 37, 52, 57, 63].includes(item.terminalType));
                    break;
                case 2:
                    serialNumList = serialNumArr.filter(item => [35].includes(item.terminalType));
                    break;
                case 3:
                    serialNumList = serialNumArr.filter(item => [1].includes(item.terminalType));
                    break;
                case 4:
                    serialNumList = serialNumArr.filter(item => [85].includes(item.terminalType));
                    break;
            }
            serialNums = serialNumList.map(item => item.terminalSerial);
            this.curSerialNums = serialNums.join(",");
            if (this.siteMonitorType == 3) {
                this.getInsectPicList();
                return
            }
            let params = { "serialNums": serialNums.join(","), "startDate": startDate, "endDate": endDate };
            tpHttp.post(this, "action=com.top.local.hsfpl.operationMonitorScreen.batchQuerySensorRealData", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && data.length) {
                    this.sensorList = data;
                    let serialNumArr = [], arr = [];
                    data.forEach(item => {
                        let obj = this.projectTerminalList.find(item2 => item2.serial_num == item.serial_num);
                        if (!serialNumArr.includes(item.serial_num)) {
                            serialNumArr.push(item.serial_num);
                            arr.push({
                                name: item.serial_num,
                                serial_num: (obj && obj.terminal_name || "") + "(" + item.serial_num + ")",
                                data: []
                            })
                        } else {
                            arr.map(ele => {
                                if (ele.name == item.serial_num) {
                                    ele.data.push(item);
                                }
                            })
                        }
                    });
                    arr.map(item => {
                        item.collect_time = item.data[0] && item.data[0].collect_time && item.data[0].collect_time.substring(0, 10) || "--";
                        this.tableHeader.map(ele => {
                            if (ele.sensor_type_id && !item[ele.props]) {
                                let obj = item.data.find(el => el.sensor_type_id == ele.sensor_type_id) || {};
                                item[ele.props] = sensorValue(obj, key = 'device_value');
                                if (!ele.labels) {
                                    ele.labels = obj.sensor_type_name + '(' + obj.sensor_unit + ')';
                                }
                            }
                        })
                    })
                    this.tableData = arr;
                } else {
                    this.tableData = [];
                }
                this.tableLoading = false;
            })
        },
        getSensorRealData2() {
            this.tableLoading = true;
            let date = tpUtils.parseTime(new Date().getTime(), "{y}-{m}-{d}");
            let serialNumArr = [], serialNumList = [], serialNums = "";
            if (this.siteMonitorProject === "") {
                let arr = []
                this.siteMonitorProjectList.forEach(item => {
                    arr = arr.concat(item.term_list || []);
                });
                serialNumArr = arr;
            } else {
                let obj = this.siteMonitorProjectList.find(item => item.projectId == this.siteMonitorProject);
                serialNumArr = obj && obj.term_list || [];
            }
            switch (this.siteMonitorType) {
                case 1:
                    serialNumList = serialNumArr.filter(item => [3, 20, 37, 52, 57, 63].includes(item.terminalType));
                    break;
                case 2:
                    serialNumList = serialNumArr.filter(item => [35].includes(item.terminalType));
                    break;
                case 3:
                    serialNumList = serialNumArr.filter(item => [1].includes(item.terminalType));
                    break;
                case 4:
                    serialNumList = serialNumArr.filter(item => [85].includes(item.terminalType));
                    break;
            }
            serialNums = serialNumList.map(item => item.terminalSerial);
            this.curSerialNums = serialNums.join(",");
            if (this.siteMonitorType == 3) {
                this.getInsectPicList();
                return
            }

            let params = { "serialNums": this.curSerialNums, "date": date };
            tpHttp.post(this, "action=com.top.local.hsfpl.operationMonitorScreen.loadSensorLastValueBySerialNums", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && data.length) {
                    data.map(item => {
                        item.collect_time = item.sensor_list[0] && item.sensor_list[0].collect_time && item.sensor_list[0].collect_time.substring(0, 10) || date;
                        this.tableHeader.map(ele => {
                            if (ele.sensor_type_id && !item[ele.props]) {
                                let obj = item.sensor_list.find(el => el.sensor_type_id == ele.sensor_type_id) || {};
                                item[ele.props] = sensorValue(obj, key = 'last_value');
                                if (!ele.labels) {
                                    ele.labels = obj.sensor_type_name + '(' + obj.sensor_unit + ')';
                                }
                            }
                        })
                    })
                    this.tableData = data;
                } else {
                    this.tableData = [];
                }
                this.tableLoading = false;
            })
        },
        /**
         * 获取虫情图片信息
         */
        getInsectPicList() {
            this.tableLoading = true;
            if (this.insectList.length != 0 && this.insectList.length >= this.insectPagaination.total) {
                return
            }
            let params = { "serialNums": this.curSerialNums, "page": this.insectPagaination.page, "size": this.insectPagaination.size };
            tpHttp.post(this, "action=com.top.local.hsfpl.operationMonitorScreen.searchCqImgsPage", { param: JSON.stringify(params) }, (data, code, message) => {
                if (code == 0 && data && data.list && data.list.length) {
                    let insectList = data.list.map(item => {
                        let allNum = 0;
                        if (item.insectInfo && item.insectInfo.length) {
                            allNum = item.insectInfo.reduce((pre, cur) => {
                                return pre + cur.number
                            }, 0);
                        } else {
                            item.insectInfo = [];
                        }
                        item.allNum = allNum;
                        return item;
                    })
                    this.insectPagaination.total = data.total;
                    this.insectList = this.insectList.concat(insectList);
                    if (this.insectSwiper) {
                        this.insectSwiper.update();
                    } else {
                        this.$nextTick(() => {
                            this.initInsectCarousel();
                        })
                    }

                } else {
                    this.insectList = [];
                }
                this.tableLoading = false;
            })
        },
        /**
         * 虫情详情点击
         */
        indectDetailClick(item) {
            this.detailsData.visible = true;
            this.$nextTick(() => {
                this.initKonva(item);
            })
        },
        // 初始化konva
        async initKonva(item) {
            let dom = 'konva-container';
            const konva_width = document.querySelector(`.${dom}`).offsetWidth;
            const konva_height = document.querySelector(`.${dom}`).offsetHeight;
            this.detailsData.stage = new Konva.Stage({ container: `.${dom}`, width: konva_width, height: konva_height });
            this.detailsData.layer = new Konva.Layer();
            this.detailsData.stage.add(this.detailsData.layer);
            this.detailsData.loading = true;
            const { width, height, img } = await loadImage(item.orignal_url);
            this.detailsData.loading = false;
            const ratio = width / height;
            const scale = konva_width / width;
            this.detailsData.scale = scale;
            const imgNode_width = konva_width; //宽度固定写死，宽度更具计算得到
            const imgNode_height = imgNode_width / ratio;

            // 创建组
            const group = new Konva.Group({
                draggable: false,
                name: 'group',
                x: (konva_width - imgNode_width) / 2,   // 默认居中位置
                y: (konva_height - imgNode_height) / 2,   // 默认居中位置,
                width: width,
                height: height,
                scaleX: scale,
                scaleY: scale,
            });

            // 创建图片元素
            const imgNode = new Konva.Image({
                draggable: false,
                x: 0,
                y: 0,
                id: 'imgNode',
                width: width,
                height: height,
                image: img,
            })
            group.add(imgNode);
            this.detailsData.group = group;
            this.detailsData.layer.add(group);
            this.detailsData.layer.draw();
            this.getinsectMark(item.insectInfo || [])
        },

        // 添加虫子标记层
        addMaskLayer(list) {
            list.forEach((item, index) => {
                const { position = [], count, type, bgColor } = item || {};
                console.log(bgColor)
                if (position && position.length > 0) {
                    position.forEach((ele, i) => {
                        const { rb, lt } = ele;
                        const [x1, y1] = lt.split(',');
                        const [x2, y2] = rb.split(',');
                        const width = x2 - x1;
                        const height = y2 - y1;
                        const poly = new Konva.Rect({
                            x: x1,
                            y: y1,
                            width: width,
                            height: height,
                            fill: bgColor + '20',
                            stroke: bgColor,
                            strokeWidth: 2,
                            strokeScaleEnabled: false,
                            dashEnabled: true,
                            dash: [5, 5]
                        });

                        const text = new Konva.Text({
                            x: x1,
                            y: y1,
                            width: width,
                            height: height,
                            text: i + 1,
                            fontSize: 15 / this.detailsData.scale,
                            fill: '#fff',
                            align: 'center',
                            verticalAlign: 'middle',
                        });

                        this.detailsData.group.add(poly);
                        this.detailsData.group.add(text);
                        this.detailsData.layer.add(this.detailsData.group);
                        this.detailsData.layer.draw();
                    })
                }
            })
        },

        // 获取虫子标记数据
        async getinsectMark(data = []) {
            let list = data.map(item => {
                return {
                    bgColor: item.color,
                    insect_name: item.insectTypeName,
                    position: item.square ? JSON.parse(item.square) : [],
                    number: item.number
                }
            })
            this.detailsData.legendList = list;
            this.addMaskLayer(list);
        },
        /**
         * 站点类型点击
         * @param {*} row 
         */
        siteMonitorTypeClick(row) {
            if (this.tableLoading) {
                return
            }
            this.siteMonitorType = row.value;
            if (row.value == 1) {
                this.tableHeader = this.weatherTableHeader;
            } else if (row.value == 2) {
                this.tableHeader = this.soilTableHeader;
            } else if (row.value == 4) {
                this.tableHeader = this.waterTableHeader;
            } else if (row.value == 3) {
                this.tableHeader = [];
                this.tableData = [];
                this.insectList = [];
                this.insectPagaination = {
                    page: 1,
                    size: 20,
                    total: 0
                }
            };
            this.getSensorRealData();
        },
        /**
         * 初始化虫情图片轮播
         */
        initInsectCarousel() {
            if (this.insectSwiper) {
                this.insectSwiper.destroy();
                this.insectSwiper = null;
            }
            let _this = this;
            var swiper = new Swiper(".myInsectSwiper", {
                slidesPerView: "auto",
                spaceBetween: 20,
                navigation: {
                    nextEl: ".insect-swiper-next",
                    prevEl: ".insect-swiper-prev",
                },
                on: {
                    reachEnd: function () {
                        _this.insectPagaination.page++;
                        _this.getInsectPicList();
                    },
                },
            });
            this.insectSwiper = swiper;
        },
    },
    mounted() {
        this.tableHeader = this.weatherTableHeader;
    }
});



/**
 * 传感器值
 * @param sensor
 * @returns {string}
 */
function sensorValue(sensor, key = 'device_value') {
    let { sensor_type_id, precision = 1, sensor_unit = '' } = sensor;
    let value = null;
    if (sensor[key] != undefined && !isNaN(sensor[key])) {
        if (sensor_type_id != 180) {
            value = parseFloat(sensor[key].toFixed(precision));
        } else {
            //风向特殊处理
            return windDirection(sensor[key]);
        }
    } else {
        value = '--';
    }
    return value;
}